from models import Studio,Log
from freeze import zip_studio
from subprocess import Popen
from django.conf import settings
import os

    
def auto_deploy():
    for studio in Studio.objects.all():
        if studio.auto_deploy and studio.is_deployable() and\
        (not studio.status.last_deploy or studio.status.last_deploy < studio.last_save):
            deploy_studio(studio)
    l=Log(category='deloy.info',type='normal',title='depoy studios success')
    l.save()

def deploy_studio(studio):
    path = zip_studio(studio)
    if getattr(settings,'ALLOW_DEPLOY',False) and os.path.exists(path) \
       and studio.domain:
        upload_to_google(path, studio.domain)
    print('upload %s complete')
    studio.status.done_deploy()
   
    

def upload_to_google(path,domain):
    src= settings.BASE_DIR
    media = settings.MEDIA_ROOT
    gc_sdk=settings.GC_SDK
    print('upload to google cloud')
    gc = 'echo start \n'
    gc +='export PATH="{gc_sdk}":$PATH\n'.format(gc_sdk=gc_sdk)
    gc += 'echo my \n'
    gc += 'export CLOUDSDK_PYTHON_SITEPACKAGES=1\n'
    gc += 'echo out\n'
    gc +='gcloud auth activate-service-account nexa-website-storage@nexa-website.iam.gserviceaccount.com  \
    --key-file {keyfile}\n'.format(keyfile = os.path.join(src,'static','keyfile.txt'))
    
    gc+= 'echo load\n'
    gc += 'gsutil rsync -R "{path}" gs://{domain}\n'.format(path=path,domain=domain)
    gc += 'echo load over \n'
    gc += 'gsutil acl ch -r -u AllUsers:R gs://{domain}\n'.format(domain=domain)
    gc += 'echo end \n'
    with open(os.path.join(media,'tmp_run'),'w') as f:
        f.write(gc)
    Popen('. %s'%os.path.join(media,'tmp_run'),shell=True,executable='/bin/bash')    